<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/2
 * Time: 11:51
 */

namespace app\admin\controller;


use app\reuse\controller\ResponseJson;
use app\service\ResourceService;
use Redis\Redis;
use think\App;
use think\Controller;
use think\Db;
use think\Session;

class Active extends Common
{
    use ResponseJson;

    function __construct(App $app = null)
    {
        parent::__construct($app);
    }
    
    /**
     * @return array|mixed|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 满送活动
     */
    function full_delivery()
    {
        $action = input('get.action');
        if ($action == 'list') {
            # 加载满送列表数据
            $info = Db::table('full_delivery')->order(array('amount' => 'desc'))->select();
            return $this->jsonSuccessData(array('data' => $info, 'count' => count($info)));
        }
        if ($action == 'view') {
            # 加载满送列表页面
            return $this->fetch('/full/list');
        }
        if ($action == 'addView') {
            # 加载满送添加页面
            return $this->fetch('/full/add');
        }
        if ($action == 'add') {
            # 添加满送数据
            $amount = input('post.amount');
            $give = input('post.give_num');
            $insertInfo = array();
            if (!empty($amount)) {
                for ($i = 0; $i < count($amount); $i++) {
                    array_push($insertInfo, array('amount' => $amount[$i], 'give_num' => $give[$i]));
                }
            }
            if (!empty($insertInfo)) {
                Db::table('full_delivery')->insertAll($insertInfo);
            }
            return array('status' => true);
        }
        if ($action == 'del') {
            # 删除
            $id = input('post.id');
            if (!empty($id)) {
                Db::table('full_delivery')->where(array('id' => $id))->delete();
                return array('status' => true);
            } else {
                return array('status' => false, 'msg' => '参数为空');
            }
        }
        if ($action == 'write') {
            # 修改信息
            $id = input('post.id');
            $value = input('post.value');
            $field = input('post.field');
            if (!empty($id) and !empty($field)) {
                if (empty($value)) {
                    $value = 0;
                }
                Db::table('full_delivery')->where(array('id' => $id))->update(array($field => $value));
                return array('status' => true, 'msg' => '修改成功');
            } else {
                return array('status' => false, 'msg' => '缺少参数');
            }
        }
    }

    /**
     * @return mixed|string
     * @throws \think\exception\DbException
     * @context 大转轮列表
     */
    function roulette_index()
    {
        if (input("get.action") != "ajax") {
            return $this->fetch();
        } else {
            $where = "act.id > 0";
            $searchParams = input("post.searchParams");
            if (!empty($searchParams['search'])) {
                $where .= " and act.title like '%" . $searchParams['search'] . "%'";
            }
            if (!empty($searchParams['start_time'])) {
                $where .= " and act.start_time<='" . $searchParams['start_time'] . "' and act.end_time >='" . $searchParams['start_time'] . "'";
            }
            if (!empty($searchParams['end_time'])) {
                $where .= " and act.end_time>='" . $searchParams['end_time'] . "' and act.start_time<='" . $searchParams['end_time'] . "'";
            }
            $listRows = empty(input("post.limit")) ? 10 : input("post.limit");
            $list = Db::table("active act")
                ->field("act.*,if(act.status=1,
                (case 
                    when act.end_time<'" . date("Y-m-d H:i:s") . "' then 3
                    when act.start_time>'" . date("Y-m-d H:i:s") . "' then 2
                    else 1 end 
                ),3) status_mark,
                coalesce((select count(member_code) from active_joinlog aj where aj.active_id = act.id and join_status=1
                ),0) party_num
                ")
                ->where(array("act.category" => 1))
                ->where($where)
                ->order("status_mark")
                ->paginate($listRows, false, ['query' => request()->param()]);

            return $this->jsonSuccessData($list);
        }
    }

    /**
     * @return array|mixed
     * @context 大转轮活动添加
     */
    function roulette_add()
    {
        if (input("get.action") != "ajax") {
            Prize::clearPrizeStorage(1);
            return $this->fetch();
        } else {
            $param = input("post.");
            $prize = Prize::getsPrizeStorage(1);
            if (!empty($prize)) {
                $rate_count = array_sum(array_column($prize, 'reward_rate'));
                if ($rate_count > 1) {
                    return array("status" => false, "msg" => "奖品概率不能超过100%");
                }
            } else {
                return array("status" => false, "msg" => "请输入奖品");
            }
            $param['category'] = 1;
            $res = Db::table("active")->insertGetId($param);
            if ($res) {
                $_array = array();
                foreach ($prize as $k => $v) {
                    array_push($_array, array("active_id" => $res, "category" => $v['category'], "title" => $v['title'],
                        "reward_num" => $v['reward_num'], "stock_num" => $v['stock_num'], "unit" => $v['unit'], "reward_rate" => $v['reward_rate'],
                        "reward_times" => $v['reward_times'], "validity_period" => $v['validity_period'], "voucher_id" => $v['voucher_id'],
                        "worth" => $v['worth'], "detail" => $v['detail'], "active_category" => 1));
                }
                Db::table("active_reward")->insertAll($_array);
                Prize::clearPrizeStorage(1);
                $this->changeRedis();
                return array("status" => true);
            } else {
                return array("status" => false, "msg" => "添加失败");
            }
        }
    }

    /**
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 大转轮修改
     */
    function roulette_write()
    {
        if (input("get.action") != 'ajax') {
            $id = input('get.id');
            $info = Db::table("active")->where(array("id" => $id))->find();
            $this->assign("info", $info);
            Prize::setPrizeStorage($info['id'], 1, 1);
            return $this->fetch();
        } else {
            $param = input("post.");
            $prize = Prize::getsPrizeStorage(1);
            if (!empty($prize)) {
                $rate_count = array_sum(array_column($prize, 'reward_rate'));
                if ($rate_count > 1) {
                    return array("status" => false, "msg" => "奖品概率不能超过100%");
                }
            } else {
                return array("status" => false, "msg" => "请输入奖品");
            }
            $param['category'] = 1;
            $id = $param['id'];
            unset($param['id']);
            Db::table("active")->where(array("id" => $id))->update($param);
            $_array = array();
            $_id_con = array();
            foreach ($prize as $k => $v) {
                $_need_array = array("category" => $v['category'], "title" => $v['title'],
                    "reward_num" => $v['reward_num'], "stock_num" => $v['stock_num'], "unit" => $v['unit'], "reward_rate" => $v['reward_rate'],
                    "reward_times" => $v['reward_times'], "validity_period" => $v['validity_period'], "voucher_id" => $v['voucher_id'],
                    "worth" => $v['worth'], "detail" => $v['detail'], "active_category" => 1);
                if ($v['storage'] == "DB") {
                    array_push($_id_con, $v['id']);
                    Db::table("active_reward")->where(array("id" => $v['id']))->update($_need_array);
                } else {
                    $_need_array['active_id'] = $id;
                    array_push($_array, $_need_array);
                }
            }
            if (!empty($_id_con)) {
                $id_str = implode(',', $_id_con);
                # 删除不在需要值的数据
                Db::table("active_reward")->where(array("active_id" => $id, "active_category" => 1))->where("id not in ($id_str)")->delete();
            }
            if (!empty($_array)) {
                Db::table("active_reward")->insertAll($_array);
            }
            Prize::clearPrizeStorage(1);
            $this->changeRedis($id);
            return array("status" => true);
        }
    }

    function changeRedis($activeId = 0)
    {
        $redis = new Redis();
        $redis->hDel('bigRunner', 'info');
        if (!empty($activeId))
            $redis->hDel('bigRunnerPrize', strval($activeId));
    }

    function roulette_delete()
    {

    }

    /**
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 大转轮统计
     */
    function roulette_static()
    {
        $active_id = input("get.active_id");
        if (input("get.action") != "ajax") {
            $this->assign("active_id", $active_id);
            return $this->fetch();
        } else {
            $where = null;
            $start_time = input("post.start_time");
            $end_time = input("post.end_time");
            if (empty($start_time)) {
                $start_time = date("Y-m");
            }
            if (empty($end_time)) {
                $end_time = date("Y-m");
            }

            $list = Db::table("active_rewardlog ar")
                ->field("ar.reward_title,ar.reward_id,date_format(ar.create_time,'%Y-%m-%d') reward_date,sum(reward_num) count_num")
                ->where(array("ar.active_id" => $active_id))
                ->where("date_format(ar.create_time,'%Y-%m')>='" . $start_time . "' and date_format(ar.create_time,'%Y-%m')<='" . $end_time . "'")
                ->where($where)
                ->group("date_format(ar.create_time,'%Y-%m-%d'),ar.reward_id")
                ->order("reward_date,reward_id")
                ->select();
            $list_member = Db::table("active_rewardlog ar")
                ->field("count(distinct ar.member_code) count_member,date_format(ar.create_time,'%Y-%m-%d') reward_date")
                ->where(array("ar.active_id" => $active_id))
                ->where("date_format(ar.create_time,'%Y-%m')>='" . $start_time . "' and date_format(ar.create_time,'%Y-%m')<='" . $end_time . "'")
                ->where($where)
                ->group("date_format(ar.create_time,'%Y-%m-%d')")
                ->order("reward_date")
                ->select();
            $_array = array_reduce($list_member, function (&$_array, $value) {
                $_array[$value['reward_date']] = $value['count_member'];
                return $_array;
            });
            $_return = array();

            $_prize_array = array("member_count" => array("name" => "参与人数", "type" => 'line', "data" => array()));
            if (!empty($list) and !empty($_array)) {
                foreach ($list as $k => $v) {
                    if (!array_key_exists($v['reward_id'], $_prize_array)) {
                        $_prize_array[$v['reward_id']] = array("name" => $v['reward_title'], "type" => 'line', "data" => array());
                    }
                    if (!array_key_exists($v['reward_date'], $_return)) {
                        $_return[$v['reward_date']] = array("member_count" => $_array[$v['reward_date']]);
                    }
                    $_return[$v['reward_date']][$v["reward_id"]] = $v["count_num"];
                }
                foreach ($_return as $k => $v) {
                    # 放入奖品数组
                    foreach ($_prize_array as $pk => $pv) {
                        if (array_key_exists($pk, $v)) {
                            array_push($_prize_array[$pk]['data'], intval($v[$pk]));
                        } else {
                            array_push($_prize_array[$pk]['data'], 0);
                        }
                    }
                }
                # 返回时间数组、奖品数组
                $_data = array("title_array" => array_column(array_values($_prize_array), "name"), "date_array" => array_keys($_return), "data_array" => array_values($_prize_array));
                return array("status" => true, "data" => $_data);
            } else {
                return array("status" => false);
            }
        }
    }

    /**
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 签到列表
     */
    function sign_index()
    {
        if (input("get.action") != 'ajax') {
            $switch = Db::table("system_switch")->field("sign_switch")->where(array("id" => 1))->find();
            $this->assign("switch", $switch['sign_switch']);
            return $this->fetch();
        } else {
            $list = Db::table("sign_set ss")
                ->field("ss.*,if((select count(ar.id) from  active_reward ar where ar.active_category=4 and ar.active_id=ss.id)>0,'有','无') sign_prize")
                ->select();
            return $this->jsonSuccessData($list);
        }
    }

    /**
     * @return mixed|string
     * @throws \think\exception\DbException
     * @context 签到添加奖品
     */
    function sign_detail()
    {
        $sign_day = input("get.sign_day");
        if (input("get.action") != 'ajax') {
            $this->assign("sign_day", $sign_day);
            return $this->fetch();
        } else {
            $list = Db::table("active_reward ar")
                ->field("ar.*,vo.title voucher_title,vo.price voucher_price,
                (case ar.category when 1 then '积分'
                when 2 then '金币'
                when 3 then '卡券'
                when 4 then '恢复券' end) category_title")
                ->join("voucher vo", "ar.voucher_id=vo.id and ar.category=3", "left")
                ->where(array("ar.active_id" => $sign_day, "ar.active_category" => 4))
                ->paginate(20, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($list);
        }
    }

    /**
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 修改签到开关
     */
    function changeSwitch()
    {
        $mark = input("post.mark");
        $switch_value = input("post.switch_value");
        Db::table("system_switch")->where(array("id" => 1))->update(array($mark => $switch_value));
        return true;
    }

    /**
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 签到统计
     */
    function sign_static()
    {
        if (input("get.action") != 'ajax') {
            return $this->fetch();
        } else {
            $where = null;
            $start_time = input("post.start_time");
            $end_time = input("post.end_time");
            if (empty($start_time)) {
                $start_time = date("Y-m");
            }
            if (empty($end_time)) {
                $end_time = date("Y-m");
            }
            $day_list = Db::table("log_member_sign lms")
                ->field("date(lms.create_time) sign_date,count(distinct lms.member_code) sign_member")
                ->where("date_format(lms.create_time,'%Y-%m')>='" . $start_time . "' and date_format(lms.create_time,'%Y-%m')<='" . $end_time . "'")
                ->group("date_format(lms.create_time,'%Y-%m-%d')")
                ->order("sign_date")
                ->select();

            $month_list = Db::table("log_member_sign lms")
                ->field("date_format(lms.create_time,'%Y-%m') sign_date,count(lms.member_code) sign_member")
                ->where("date_format(lms.create_time,'%Y')>='" . date("Y", strtotime($start_time)) . "' and date_format(lms.create_time,'%Y')<='" . date("Y", strtotime($end_time)) . "'")
                ->group("date_format(lms.create_time,'%Y-%m')")
                ->order("sign_date")
                ->select();
            $_return_day = array("date_array" => array_column($day_list, 'sign_date'), "data_array" => array(array("name" => "日签到人数", "type" => 'line', "data" => array_column($day_list, "sign_member"))));
            $_return_month = array("date_array" => array_column($month_list, "sign_date"), "data_array" => array(array("name" => "月签到人数", "type" => "line", "data" => array_column($month_list, "sign_member"))));
            return array("status" => true, "day" => $_return_day, "month" => $_return_month);
        }
    }

    /**
     * @return mixed|string
     * @throws \think\exception\DbException
     * @context 任务列表
     */
    function task_index()
    {
        if (input('get.action') != "ajax") {
            return $this->fetch();
        } else {
            $where = "main_task=2";
            $searchParams = input("post.searchParams");
            if (!empty($searchParams['search'])) {
                $where .= " and task_title like '%" . $searchParams['search'] . "%'";
            }
            if (!empty($searchParams['task_type'])) {
                $where .= " and task_type={$searchParams['task_type']}";
            }
            $listRows = empty(input("post.limit")) ? 10 : input("post.limit");
            $list = Db::table("task")
                ->field("task.*,(case task_status when 1 then '进行中' when 2 then '已下架' end) status_mark,
                (case circulation when 1 then '是' when 2 then '否' end) circulation_title")
                ->where("task_status!=3")
                ->where($where)
                ->order("task_status")
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($list);
        }
    }

    /**
     * @return array|mixed
     * @context 任务添加
     */
    function task_add()
    {
        if (input("get.action") != 'ajax') {
            Prize::clearPrizeStorage(2);
            return $this->fetch();
        } else {
            $param = input("post.");
            $prize = Prize::getsPrizeStorage(2);
            if (empty($prize)) {
                return array("status" => false, "msg" => "请输入奖品");
            }
            $res = Db::table("task")->insertGetId($param);
            if ($res) {
                $_array = array();
                foreach ($prize as $k => $v) {
                    array_push($_array, array("active_id" => $res, "category" => $v['category'], "title" => $v['title'],
                        "reward_num" => $v['reward_num'], "stock_num" => $v['stock_num'], "unit" => $v['unit'], "reward_rate" => $v['reward_rate'],
                        "reward_times" => $v['reward_times'], "validity_period" => $v['validity_period'], "voucher_id" => $v['voucher_id'],
                        "worth" => $v['worth'], "detail" => $v['detail'], "active_category" => 2));
                }
                Db::table("active_reward")->insertAll($_array);
                Prize::clearPrizeStorage(2);
                return array("status" => true);
            } else {
                return array("status" => false, "msg" => "系统错误");
            }
        }
    }

    /**
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 任务修改
     */
    function task_write()
    {
        if (input("get.action") != 'ajax') {
            $id = input('get.id');
            $info = Db::table("task")->where(array("id" => $id))->find();
            $this->assign("info", $info);
            Prize::setPrizeStorage($id, 2, 2);
            return $this->fetch();
        } else {
            $param = input("post.");
            $prize = Prize::getsPrizeStorage(2);
            if (empty($prize)) {
                return array("status" => false, "msg" => "请输入奖品");
            }
            $id = $param['id'];
            unset($param['id']);
            Db::table("task")->where(array("id" => $id))->update($param);
            $_array = array();
            $_id_con = array();
            foreach ($prize as $k => $v) {
                $_need_array = array("category" => $v['category'], "title" => $v['title'],
                    "reward_num" => $v['reward_num'], "stock_num" => $v['stock_num'], "unit" => $v['unit'], "reward_rate" => $v['reward_rate'],
                    "reward_times" => $v['reward_times'], "validity_period" => $v['validity_period'], "voucher_id" => $v['voucher_id'],
                    "worth" => $v['worth'], "detail" => $v['detail'], "active_category" => 2);
                if ($v['storage'] == "DB") {
                    array_push($_id_con, $v['id']);
                    Db::table("active_reward")->where(array("id" => $v['id']))->update($_need_array);
                } else {
                    $_need_array['active_id'] = $id;
                    array_push($_array, $_need_array);
                }
            }
            if (!empty($_id_con)) {
                $id_str = implode(',', $_id_con);
                # 删除不在需要值的数据
                Db::table("active_reward")->where(array("active_id" => $id, "active_category" => 2))->where("id not in ($id_str)")->delete();
            }
            if (!empty($_array)) {
                Db::table("active_reward")->insertAll($_array);
            }
            Prize::clearPrizeStorage(2);
            return array("status" => true);
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 任务删除
     */
    function task_delete()
    {
        $id = input("post.id");
        Db::table("task")->where(array("id" => $id))->update(array("task_status" => 3));
        return array("status" => true);
    }

    /**
     * @return mixed|string
     * @throws \think\exception\DbException
     * @context 每日答题列表
     */
    function daliyanswer_index()
    {
        if (input("get.action") != 'ajax') {
            return $this->fetch();
        } else {
            $where = "act.id > 0";
            $searchParams = input("post.searchParams");
            if (!empty($searchParams['search'])) {
                $where .= " and act.title like '%" . $searchParams['search'] . "%'";
            }
            if (!empty($searchParams['start_time'])) {
                $where .= " and act.start_time<='" . $searchParams['start_time'] . "' and act.end_time>='" . $searchParams['start_time'] . "'";
            }
            if (!empty($searchParams['end_time'])) {
                $where .= " and act.end_time>='" . $searchParams['end_time'] . "' and act.start_time<='" . $searchParams['end_time'] . "'";
            }
            $listRows = empty(input("post.limit")) ? 10 : input("post.limit");
            $list = Db::table("active act")
                ->field("act.*,if(act.status=1,
                (case 
                    when act.end_time<'" . date("Y-m-d H:i:s") . "' then 3
                    when act.start_time>'" . date("Y-m-d H:i:s") . "' then 2
                    else 1 end 
                ),'已下架') status_mark,
                coalesce((select count(member_code) from active_joinlog aj where aj.active_id = act.id and join_status=1
                group by aj.member_code),0) party_num
                ")
                ->where(array("act.category" => 2))
                ->where($where)
                ->order("status_mark")
                ->paginate($listRows, false, ['query' => request()->param()]);

            return $this->jsonSuccessData($list);
        }
    }

    /**
     * @return array|mixed
     * @context 每日答题添加
     */
    function daliyanswer_add()
    {
        if (input("get.action") != 'ajax') {
            return $this->fetch();
        } else {
            $param = input("post.");
            if (empty($param['question_id'])) {
                return array("status" => false, "msg" => "请选择题目");
            }
            $param['question_id'] = implode(',', $param['question_id']);
            $param['category'] = 2;
            $prize = Prize::getsPrizeStorage(3);
            if (!empty($prize)) {
                $rate_count = array_sum(array_column($prize, 'reward_rate'));
                if ($rate_count > 1) {
                    return array("status" => false, "msg" => "奖品概率不能超过100%");
                }
            } else {
                return array("status" => false, "msg" => "请输入奖品");
            }
            $res = Db::table("active")->insertGetId($param);
            if ($res) {
                $_array = array();
                foreach ($prize as $k => $v) {
                    array_push($_array, array("active_id" => $res, "category" => $v['category'], "title" => $v['title'],
                        "reward_num" => $v['reward_num'], "stock_num" => $v['stock_num'], "unit" => $v['unit'], "reward_rate" => $v['reward_rate'],
                        "reward_times" => $v['reward_times'], "validity_period" => $v['validity_period'], "voucher_id" => $v['voucher_id'],
                        "worth" => $v['worth'], "detail" => $v['detail'], "active_category" => 3));
                }
                Db::table("active_reward")->insertAll($_array);
                Prize::clearPrizeStorage(3);
                return array("status" => true);
            }
        }
    }

    /**
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 每日答题修改
     */
    function daliyanswer_write()
    {
        if (input("get.action") != 'ajax') {
//            $id=input('get.id');
//            $info=Db::table("active")->where(array("id"=>$id))->find();
//            $this->assign("info",$info);
//            $this->assign("id_con",implode(',',array_map("change_to_quotes",explode(',',$info['question_id']))));
//            $question=Db::table("question_bank")->field("id,title")->where("id in ({$info['question_id']})")->select();
//            $this->assign("question",$question);
            Prize::setPrizeStorage(0, 3, 3);
            return $this->fetch();
        } else {
//            $param=input("post.");
            $prize = Prize::getsPrizeStorage(3);
            if (!empty($prize)) {
                $rate_count = array_sum(array_column($prize, 'reward_rate'));
                if ($rate_count > 1) {
                    return array("status" => false, "msg" => "奖品概率不能超过100%");
                }
            } else {
                return array("status" => false, "msg" => "请输入奖品");
            }
//            if(empty($param['question_id'])){
//                return array("status"=>false,"msg"=>"请选择题目");
//            }
//            $param['question_id']=implode(',',$param['question_id']);
//            $param['category']=2;
//            $id=$param['id'];
//            unset($param['id']);
//            Db::table("active")->where(array("id"=>$id))->update($param);
            $_array = array();
            $_id_con = array();
            foreach ($prize as $k => $v) {
                $_need_array = array("category" => $v['category'], "title" => $v['title'],
                    "reward_num" => $v['reward_num'], "stock_num" => $v['stock_num'], "unit" => $v['unit'], "reward_rate" => $v['reward_rate'],
                    "reward_times" => $v['reward_times'], "validity_period" => $v['validity_period'], "voucher_id" => $v['voucher_id'],
                    "worth" => $v['worth'], "detail" => $v['detail'], "active_category" => 3);
                if ($v['storage'] == "DB") {
                    array_push($_id_con, $v['id']);
                    Db::table("active_reward")->where(array("id" => $v['id']))->update($_need_array);
                } else {
                    $_need_array['active_id'] = 0;
                    array_push($_array, $_need_array);
                }
            }
            if (!empty($_id_con)) {
                $id_str = implode(',', $_id_con);
                # 删除不在需要值的数据
                Db::table("active_reward")->where(array("active_category" => 3))->where("id not in ($id_str)")->delete();
            }
            if (!empty($_array)) {
                Db::table("active_reward")->insertAll($_array);
            }
            Prize::clearPrizeStorage(3);
            return array("status" => true);
        }
    }

    /**
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 问题设置
     */
    function set_question()
    {
        if (input("get.action") !== 'ajax') {
            $id_con = input("get.id_con");
            if (empty($id_con)) {
                $id_con_array = "";
            } else {
                $id_con_array = implode(',', array_map("change_to_quotes", explode(',', $id_con)));
            }
            $this->assign("id_con", $id_con_array);
            return $this->fetch();
        } else {
            $where = "status=1 ";
            $searchParams = input("post.searchParams");
            $all = true;
            $id_con = input("post.id_con");
            if (!empty($searchParams['search'])) {
                $all = false;
                $where .= " and title like '%" . $searchParams['search'] . "%'";
            }
            $list = Db::table("question_bank qb")->field("qb.*,if(find_in_set(qb.id,'" . $id_con . "')=0,'','true') LAY_CHECKED")->where(array("status" => 1))->where($where)->select();
            if ($all) {
                $_return = array("data" => $list, "id_con" => array_values(array_column($list, 'id')));
            } else {
                $_return = array("data" => $list);
            }
            return $this->jsonSuccessData($_return);
        }
    }

    /**
     * @return mixed|string
     * @throws \think\exception\DbException
     * @context 题目列表
     */
    function question_index()
    {
        if (input("get.action") != 'ajax') {
            return $this->fetch();
        } else {
            $where = "qb.id > 0";
            $searchParams = input("post.searchParams");
            if (!empty($searchParams['search'])) {
                $where .= " and qb.title like '%" . $searchParams['search'] . "%'";
            }
            if (!empty($searchParams['status'])) {
                $where .= " and qb.status={$searchParams['status']}";
            }
            $listRows = empty(input("post.limit")) ? 10 : input("post.limit");
            $list = Db::table("question_bank qb")
                ->field("qb.*,(select count(lmg.id) from log_member_question lmg where lmg.question_id=qb.id and lmg.right_status=1) right_count,
                (select count(lmg.id) from log_member_question lmg where lmg.question_id=qb.id and lmg.right_status=2) error_count,
                (select count(lmg.id) from log_member_question lmg where lmg.question_id=qb.id) join_member,
                convert(coalesce((select count(lmg.id) from log_member_question lmg where lmg.question_id=qb.id and lmg.right_status=1)/
                (select count(lmg.id) from log_member_question lmg where lmg.question_id=qb.id)*100,0),decimal(10,2)) accuracy")
                ->where($where)
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($list);
        }
    }

    /**
     * @return array|mixed
     * @context 问题添加
     */
    function question_add()
    {
        if (input("get.action") != 'ajax') {
            return $this->fetch();
        } else {
            $param = input("post.");
            $context = $param['context'];
            if (empty($context)) {
                return array("status" => false, "msg" => "答案不能为空");
            }
            $right_answer = $param['right_answer'];
            if (empty($right_answer)) {
                return array("status" => false, "msg" => "正确答案不能为空");
            }
            if ($param['type'] == 1 and array_sum($right_answer) > 1) {
                return array("status" => false, "msg" => "单选题只可以有一个正确答案");
            }
            unset($param['context']);
            unset($param['right_answer']);
            if (empty($param['status'])) {
                $param['status'] = 2;
            }
            $res = Db::table("question_bank")->insertGetId($param);
            if ($res) {
                $_array = array();
                foreach ($context as $k => $v) {
                    if (empty($right_answer[$k])) {
                        $right_answer[$k] = 2;
                    }
                    array_push($_array, array("question_id" => $res, "context" => $v, "right_answer" => $right_answer[$k]));
                }
                Db::table("question_answer")->insertAll($_array);
                return array("status" => true);
            } else {
                return array("status" => false, "msg" => "系统错误");
            }

        }
    }

    /**
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 题目修改
     */
    function question_write()
    {
        $id = input("get.id");
        if (input("get.action") !== 'ajax') {
            $info = Db::table("question_bank")->where(array("id" => $id))->find();
            $this->assign("info", $info);
            $answer_info = Db::table("question_answer")->where(array("question_id" => $id))->select();
            $this->assign("answer_info", $answer_info);
            # 正确答案有多少个
            $right_count = Db::table("question_answer")->where(array("question_id" => $id, "right_answer" => 1))->count();
            $this->assign("right_count", $right_count);
            return $this->fetch();
        } else {
            $param = input("post.");
            $context = $param['context'];
            if (empty($context)) {
                return array("status" => false, "msg" => "答案不能为空");
            }
            $right_answer = $param['right_answer'];
            if (empty($right_answer)) {
                return array("status" => false, "msg" => "正确答案不能为空");
            }
            if ($param['type'] == 1 and array_sum($right_answer) > 1) {
                return array("status" => false, "msg" => "单选题只可以有一个正确答案");
            }
            $id_coll = $param['answer_id'];
            unset($param['context']);
            unset($param['right_answer']);
            unset($param['answer_id']);
            if (empty($param['status'])) {
                $param['status'] = 2;
            }
            $res = Db::table("question_bank")->where(array("id" => $id))->update($param);
            $_array = array();
            foreach ($context as $k => $v) {
                if (empty($right_answer[$k])) {
                    $right_answer[$k] = 2;
                }
                if (!empty($id_coll) and !empty($id_coll[$k])) {
                    Db::table("question_answer")->where(array("id" => $id_coll[$k]))->update(array("context" => $v, "right_answer" => $right_answer[$k]));
                } else {
                    array_push($_array, array("question_id" => $id, "context" => $v, "right_answer" => $right_answer[$k]));
                }
            }
            if (!empty($id_coll)) {
                $id_str = implode(',', $id_coll);
                Db::table("question_answer")->where(array("question_id" => $id))->where("id not in ({$id_str})")->delete();
            }
            if (!empty($_array)) {
                Db::table("question_answer")->insertAll($_array);
            }
            return array("status" => true);
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 题目删除
     */
    function question_delete()
    {
        $id = input("post.id");
        Db::table("question_bank")->where(array("id" => $id))->delete();
        Db::table("question_answer")->where(array("question_id" => $id))->delete();
        return array("status" => true);
    }

    /**
     * @return mixed|string
     * @throws \think\exception\DbException
     * @context 积分兑换列表
     */
    function integral_exchange_index()
    {
        if (input("get.action") != "ajax") {
            return $this->fetch();
        } else {
            $where = "pro_status<3";
            $searchParams = input("post.searchParams");
            if (!empty($searchParams['search'])) {
                $where .= " and pro_title like '%" . $searchParams['search'] . "%'";
            }
            if (!empty($searchParams['pro_type'])) {
                $where .= " and pro_type={$searchParams['pro_type']}";
            }
            $listRows = empty(input("post.limit")) ? 10 : input("post.limit");
            $list = Db::table("integral_exchange")
                ->field("id,pro_title,pro_type,integral_num,pro_num,plurs_num,putaway_time,
                under_time,pro_status,if(pro_status=1,
                (case 
                    when under_time<'" . date("Y-m-d H:i:s") . "' then 3
                    when putaway_time>'" . date("Y-m-d H:i:s") . "' then 2
                    else 1 end 
                ),3) status_mark")
                ->where($where)
                ->order("status_mark")
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($list);
        }
    }

    /**
     * @return array|mixed
     * @throws \BaseException
     * @throws \think\Exception
     * @context 积分兑换添加
     */
    function integral_exchange_add()
    {
        if (input("get.action") != "ajax") {
            Session("source_upload", null);
            return $this->fetch();
        } else {
            $param = input("post.");
            if (empty($param['bannerurl'])) {
                return array("status" => false, "msg" => "请上传banner图");
            }
            if (empty($param['imgurl'])) {
                return array("status" => false, "msg" => "请上传缩略图");
            }
            $param['plurs_num'] = $param['pro_num'];
            $param['pro_status'] = 1;
            //处理多余图片
            //$in_use = array_map('wipeOffFormStr', get_images_from_html($param['detailurl']));
            $in_use = array();
            # 无用图片清理
            $banner_url = explode(',', $param['bannerurl']);
            array_push($banner_url, $param['imgurl']);
            array_push($banner_url, $param['detailurl']);
            $_img_res = array_merge($banner_url, $in_use);
            ResourceService::delCacheItem($_img_res);
            ResourceService::delUploadCache();

            unset($param['thumb_img'], $param['editor_imgs'], $param['activeBanner']);
            $res = Db::table("integral_exchange")->insert($param);
            if ($res) {
                return array("status" => true);
            } else {
                return array("status" => false, "msg" => "系统错误");
            }
        }
    }

    /**
     * @return array|mixed
     * @throws \BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 积分兑换修改
     */
    function integral_exchange_write()
    {
        if (input("get.action") != "ajax") {
            $id = input("get.id");
            Session("source_upload", null);
            $info = Db::table("integral_exchange")
                ->field("integral_exchange.*,v.price,v.title")
                ->join("voucher v", "v.id=integral_exchange.pro_number and pro_type=3", "left")
                ->where(array("integral_exchange.id" => $id))->find();
            if (!empty($info['imgurl'])) {
                ResourceService::setUploadCache($info['imgurl'], 'img');
            }
            if (!empty($info['detailurl'])) {
                ResourceService::setUploadCache($info['detailurl'], 'img');
            }
//            $_detail_img = get_images_from_html($info['detailurl']);
//            if (!empty($_detail_img)) {
//                foreach ($_detail_img as $k => $v) {
//                    ResourceService::setUploadCache(wipeOffFormStr($v), 'img');
//                }
//            }
//            $info['editor_imgs'] = join(',', $_detail_img);
            $_bannerurl = explode(",", $info["bannerurl"]);
            $this->assign("bannerArr", $_bannerurl);
            if (!empty($_bannerurl)) {
                foreach ($_bannerurl as $k => $v) {
                    ResourceService::setUploadCache($v, 'img');
                }
            }
            $info["banner_url"] = implode(',', array_map("change_to_quotes", $_bannerurl));
            $this->assign("info", $info);
            return $this->fetch();
        } else {
            $param = input("post.");

            $id = $param['id'];
            if (empty($param['bannerurl'])) {
                return array("status" => false, "msg" => "请上传banner图");
            }
            if (empty($param['imgurl'])) {
                $param['imgurl'] = $param['old_imgurl'];
            }
            if (empty($param['detailurl'])) {
                $param['detailurl'] = $param['olddetailurl'];
            }
            $diff = $param['pro_num'] - $param['old_pro_num'];
            $param['plurs_num'] = intval($param['old_plurs_num']) + $diff;
            //处理多余图片
//            $in_use = array_map('wipeOffFormStr', get_images_from_html($param['detailurl']));

            # 无用图片清理
            $banner_url = explode(',', $param['bannerurl']);
            array_push($banner_url, $param['imgurl']);
            array_push($banner_url, $param['detailurl']);
            //$_img_res = array_merge($banner_url, $in_use);
            ResourceService::delCacheItem($banner_url);
            ResourceService::delUploadCache();

            unset($param['thumb_img'], $param['editor_imgs'], $param['activeBanner'], $param['old_plurs_num'], $param['old_pro_num'], $param['id'], $param['old_imgurl'], $param['olddetailurl']);
            $res = Db::table("integral_exchange")->where(array("id" => $id))->update($param);
            return array("status" => true);
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 积分兑换删除
     */
    function integral_exchange_delete()
    {
        $id = input("post.id");
        Db::table("integral_exchange")->where(array("id" => $id))->update(array("pro_status" => 3));
        return array("status" => true);
    }
}